<template>
  <div class="main">
    <!-- 位置和天气信息 -->
    <div>
      <div v-if="ipinfo.citycode">
        <div> {{ ipinfo.province }}{{ ipinfo.city }}{{ ipinfo.district }} </div>
      </div>
      <div v-if="weather.weather">
        <div>天气：{{ weather.weather }}{{ weather.temperature }}° </div>
      </div>
    </div>

    <!-- 已经登录的情况 -->
    <div v-if="islogin" v-loading="loading">
      <el-dropdown @command="handleMenu">
        <div style="display: flex; align-items: center">
          <div><el-avatar :size="50" :src="ApiService.userlogo()" /></div>
          <el-icon class="el-icon--right">
            <arrow-down />
          </el-icon>
        </div>
        <!-- 菜单 -->
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item
              ><el-icon><Avatar /></el-icon>{{ userinfo.tbUserInfo.nickname ? userinfo.tbUserInfo.nickname : '无名' }}({{ userinfo.tbUser.username }})</el-dropdown-item
            >
            <el-dropdown-item divided command="home"
              ><el-icon><ChromeFilled /></el-icon>网站首页</el-dropdown-item
            >
            <el-dropdown-item command="userhome">
              <el-icon><HomeFilled /></el-icon>用户首页</el-dropdown-item
            >
            <el-dropdown-item divided command="userpwd"
              ><el-icon><Memo /></el-icon>修改密码</el-dropdown-item
            >
            <el-dropdown-item command="logo"
              ><el-icon><PictureRounded /></el-icon>修改用户头像</el-dropdown-item
            >
            <el-dropdown-item command="userinfo"
              ><el-icon><Document /></el-icon>修改用户信息</el-dropdown-item
            >
            <el-dropdown-item divided command="userphone"
              ><el-icon><Cellphone /></el-icon>绑定手机</el-dropdown-item
            >
            <el-dropdown-item command="usermail"
              ><el-icon><Memo /></el-icon>绑定邮箱</el-dropdown-item
            >
            <el-dropdown-item divided command="accessinfo"
              ><el-icon><Setting /></el-icon> 开发者信息</el-dropdown-item
            >
            <el-dropdown-item divided command="logout"
              ><el-icon><Eleme /></el-icon> 安全退出</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 没有登录的情况 -->
    <div v-if="!islogin">
      <ElButtonGroup>
        <el-button @click="router.push('/user/login')"
          ><el-icon><User /></el-icon>登录</el-button
        >
        <el-button @click="router.push('/user/reg')"
          ><el-icon><Present /></el-icon>注册</el-button
        >
      </ElButtonGroup>
    </div>
  </div>

  <!-- 附件信息修改对话框 -->
  <el-dialog v-model="mvissible" title="附件信息修改" @closed="queryUserInfo">
    <el-form>
      <el-form-item label="用户名" label-width="15em">
        <el-input v-model="muserinfo.nickname" />
      </el-form-item>
      <el-form-item label="自我简介" label-width="15em">
        <el-input v-model="muserinfo.info" />
      </el-form-item>
      <el-form-item label="QQ" label-width="15em">
        <el-input v-model="muserinfo.qq" />
      </el-form-item>
      <el-form-item label="微信" label-width="15em">
        <el-input v-model="muserinfo.wechat" />
      </el-form-item>
      <el-form-item label="性别" label-width="15em">
        <el-radio-group v-model="muserinfo.sex">
          <el-radio v-for="d in genders" :label="d.value">{{ d.text }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="danger" @click="mvissible = false">
          <el-icon><Close /></el-icon> 关闭</el-button
        >
        <el-button type="primary" @click="saveUserInfo" v-loading="loading">
          <el-icon><Plus /></el-icon> 保存
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 手机绑定对话框 -->
  <el-dialog v-model="mpvissible" title="手机绑定" @closed="queryUserInfo" width="25em">
    <el-form>
      <el-form-item label="手机号" label-width="5em">
        <el-input v-model="mphone.phone" />
      </el-form-item>
      <el-form-item label="验证码" label-width="5em">
        <div style="display: flex">
          <el-input v-model="mphone.code" />
          <ElButton type="primary" @click="sendPhoneCode">获取验证码</ElButton>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="danger" @click="mpvissible = false">
          <el-icon><Close /></el-icon> 关闭</el-button
        >
        <el-button type="primary" @click="saveUserPhone" v-loading="loading">
          <el-icon><Plus /></el-icon> 保存
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 邮箱绑定对话框 -->
  <el-dialog v-model="mevissible" title="邮箱绑定" @closed="queryUserInfo" width="25em">
    <el-form>
      <el-form-item label="邮箱地址" label-width="5em">
        <el-input v-model="memail.email" />
      </el-form-item>
      <el-form-item label="验证码" label-width="5em">
        <div style="display: flex">
          <el-input v-model="memail.code" />
          <ElButton type="primary" @click="sendMailCode">获取验证码</ElButton>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="danger" @click="mevissible = false">
          <el-icon><Close /></el-icon> 关闭</el-button
        >
        <el-button type="primary" @click="saveUserMail" v-loading="loading">
          <el-icon><Plus /></el-icon> 保存
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 密码修改对话框 -->
  <el-dialog v-model="mpwdvissible" title="密码修改" @closed="queryUserInfo" width="25em">
    <el-form>
      <el-form-item label="旧密码" label-width="5em">
        <el-input v-model="userPwd.oldpwd" show-password />
      </el-form-item>
      <el-form-item label="新密码" label-width="5em">
        <el-input v-model="userPwd.newpwd" show-password />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="danger" @click="mpwdvissible = false">
          <el-icon><Close /></el-icon> 关闭</el-button
        >
        <el-button type="primary" @click="saveUserPwd" v-loading="loading">
          <el-icon><Plus /></el-icon> 保存
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 开发者信息对话框 -->
  <el-dialog v-model="accessVisible" title="开发者信息">
    <div class="access-info">
      <div> accessId：&nbsp;&nbsp;&nbsp; {{ userinfo.tbUser.accessId }}</div>
      <div> accessKey：&nbsp;&nbsp;&nbsp; {{ userinfo.tbUser.accessKey }}</div>
    </div>
  </el-dialog>
</template>
<script setup lang="ts">
//#region  导入和基础变量

import { ref, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import store from '../store/index'
import { ElDropdown, ElDropdownMenu, ElDropdownItem, ElButton, ElMessage, ElDialog, ElRadio, ElInput } from 'element-plus'
import { ApiService } from '../ts/ApiService'
const { islogin, userinfo, genders } = storeToRefs(store())
const { updateUserInfo, queryUserInfo } = store()
import { useRouter } from 'vue-router'
import { UserInfo, TbUserInfoVO } from '../ts/types/User'
import FileTools from '../ts/FileTools'
import { FileInfo } from '../ts/types/FileInfo'
import { log } from '../ts/logger'
import { BaseResult } from '../ts/types/BaseResult'
const router = useRouter()

const emits = defineEmits(['statusChange'])

const loading = ref(false)

//#endregion

//#region IP信息
import ipstore from '../store/ipinfo'
const { ipinfo, weather } = storeToRefs(ipstore())

//#endregion

//#region 开发者信息
const accessVisible = ref(false)

//#endregion

//#region 菜单处理

const handleMenu = (menu: string) => {
  if ('logout' == menu) {
    logout()
  } else if ('userhome' == menu) {
    router.push('/user/main')
  } else if ('home' == menu) {
    router.push('/')
  } else if ('logo' == menu) {
    changeLogo()
  } else if ('userinfo' == menu) {
    changeUserInfo()
  } else if ('userphone' == menu) {
    mphone.value.phone = userinfo.value.tbUserInfo.phone
    mpvissible.value = true
  } else if ('usermail' == menu) {
    memail.value.email = userinfo.value.tbUserInfo.email
    mevissible.value = true
  } else if ('userpwd' == menu) {
    userPwd.value = { oldpwd: '', newpwd: '' }
    mpwdvissible.value = true
  } else if ('accessinfo' == menu) {
    accessVisible.value = true
  }
}

//#endregion

//#region 修改密码
const userPwd = ref({ oldpwd: '', newpwd: '' })
const mpwdvissible = ref(false)

const saveUserPwd = () => {
  loading.value = true
  ApiService.patch('/user/password', userPwd.value, (data: BaseResult) => {
    loading.value = false
    if (data.success) {
      ElMessage.success(data.message)
    } else {
      ElMessage.error(data.message)
    }
  })
}

//#endregion

//#region 绑定邮箱
const memail = ref({ email: '', code: '' })
const mevissible = ref(false)

const sendMailCode = () => {
  loading.value = true
  ApiService.post('/tools/sendMailCode', memail.value, (data: BaseResult) => {
    loading.value = false
    if (data.success) {
      ElMessage.success(data.message)
    } else {
      ElMessage.error(data.message)
    }
  })
}

const saveUserMail = () => {
  loading.value = true
  ApiService.patch('/user/email', memail.value, (data: BaseResult) => {
    loading.value = false
    if (data.success) {
      ElMessage.success(data.message)
    } else {
      ElMessage.error(data.message)
    }
  })
}

//#endregion

//#region 绑定手机
const mphone = ref({ phone: '', code: '' })
const mpvissible = ref(false)

const sendPhoneCode = () => {
  loading.value = true
  ApiService.post('/tools/sendPhoneCode', mphone.value, (data: BaseResult) => {
    loading.value = false
    if (data.success) {
      ElMessage.success(data.message)
    } else {
      ElMessage.error(data.message)
    }
  })
}

const saveUserPhone = () => {
  loading.value = true
  ApiService.patch('/user/phone', mphone.value, (data: BaseResult) => {
    loading.value = false
    if (data.success) {
      ElMessage.success(data.message)
    } else {
      ElMessage.error(data.message)
    }
  })
}

//#endregion

//#region 安全退出

const logout = () => {
  loading.value = true
  ApiService.delete('/auth', {}, () => {
    loading.value = false
    updateUserInfo(false, {} as UserInfo)
    emits('statusChange', false)
    router.push('/user/login')
  })
}

//#endregion

//#region 头像修改

const changeLogo = () => {
  FileTools.openOneFile((fileinfo: FileInfo) => {
    log.debug('选中的头像：', fileinfo)
    loading.value = true
    ApiService.upload('/user/logo', {}, fileinfo.file, (data: BaseResult) => {
      if (data.success) {
        setTimeout(() => {
          location.reload()
        }, 10)
      } else {
        ElMessage.error(data.message)
        loading.value = false
      }
    })
  }, 'image/*')
}

//#endregion

//#region 附加信息修改

const muserinfo = ref({} as TbUserInfoVO)
const mvissible = ref(false)
const changeUserInfo = () => {
  muserinfo.value = {
    sex: userinfo.value.tbUserInfo.sex,
    nickname: userinfo.value.tbUserInfo.nickname,
    qq: userinfo.value.tbUserInfo.qq,
    wechat: userinfo.value.tbUserInfo.wechat,
    info: userinfo.value.tbUserInfo.info,
  }
  mvissible.value = true
}

const saveUserInfo = () => {
  loading.value = true
  ApiService.put('/user', muserinfo.value, (data: BaseResult) => {
    loading.value = false
    if (data.success) {
      ElMessage.success(data.message)
    } else {
      ElMessage.error(data.message)
    }
  })
}

//#endregion

onMounted(() => {
  emits('statusChange', islogin.value)
})
</script>
``
<style lang="scss" scoped>
.access-info {
  word-break: break-all;
  word-wrap: break-word;
  > div {
    margin: 1rem;
  }
}
.main {
  padding: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
